package com.cinema.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cinema.bean.*;
import com.cinema.bean.Session;
import com.cinema.service.HallService;
import com.cinema.service.MovieService;
import com.cinema.service.SessionService;
import com.cinema.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("session")
@CrossOrigin
public class SessionController {

    @Autowired
    SessionService sessionService;
    @Autowired
    HallService hallService;
    @Autowired
    MovieService movieService;

    @GetMapping("list")
    public Result getList() {
        List<Session> list = sessionService.list();
        for (Session item:list){
            Hall hall=hallService.getById(item.getHallId());
            item.setHall(hall);
        }
        for(Session item:list){
            Movie movie=movieService.getById(item.getMovieId());
            item.setMovie(movie);
        }
        return Result.success(list);
    }

    @GetMapping("page")
    public Result getPage(Page<Session> page,
                          @RequestParam(value = "searchText", required = false) String searchText) {

        LambdaQueryWrapper<Session> wrapper = new LambdaQueryWrapper<>();

        if (!StringUtils.isEmpty(searchText)) {
            // 子查询方式
            wrapper.inSql(Session::getMovieId,
                            "SELECT movie_id FROM movie WHERE movie_name LIKE '%" + searchText + "%'")
                    .or()
                    .like(Session::getMovieId, searchText);
        }

        return Result.success(sessionService.page(page, wrapper));
    }
    @PostMapping
    public Result add(@RequestBody Session session) {
        sessionService.save(session);
        return Result.success("保存成功", session);
    }

    @DeleteMapping("/{session_id}")
    public Result delete(@PathVariable("session_id") Long sessionId) {
        boolean b = sessionService.removeById(sessionId);
        if (b) {
            return Result.success("删除成功");
        } else {
            return Result.fail(201, "删除失败");
        }
    }

    @PutMapping
    public Result edit(@RequestBody Session session) {
        boolean b = sessionService.updateById(session);
        if (b) {
            return Result.success("修改成功");
        } else {
            return Result.fail(201, "修改失败");
        }
    }
}